package com.jinlejia.erp.ui.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.AppointmentVisitAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityAppointmentVisitBinding;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.ui.mine.adapter.TimeDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jinlejia.erp.utils.StringUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;


/**
 * 约看（activity）
 */

public class AppointmentVisitActivity extends AppCompatActivity implements OnDateSetListener, YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    private String headers[] = {"约看状态", "约看日期", "客户"};
    private String state[] = {"约看状态", "未完成", "已完成", "已过期", "已取消"};
    private String time[] = {"最早日期", "最晚日期"};

    private List<View> popupViews = new ArrayList<>();

    private GirdDropDownAdapter stateAdapter;
    private TimeDropDownAdapter timeAdapter;
    private AppointmentVisitAdapter adapter;

    private ListView stateView;
    private ListView timeView;

    private TextView confirm;
    private EditText causeNumber;

    public String startTime = "";
    public String endTime = "";

    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private InputMethodManager imm;

    private ActivityAppointmentVisitBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_appointment_visit);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initEvent();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        getData();
        binding.include.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.include.refreshLayout.setOnRefreshListener(this);
        //init state menu
        stateView = new ListView(this);
        stateAdapter = new GirdDropDownAdapter(this, Arrays.asList(state));
        stateView.setAdapter(stateAdapter);

        //init time menu
        final View priceAreaFooter = this.getLayoutInflater().inflate(R.layout.time_menu_footer, null);
        timeView = new ListView(this);
        timeAdapter = new TimeDropDownAdapter(this, Arrays.asList(time));
        timeView.addFooterView(priceAreaFooter);
        timeView.setAdapter(timeAdapter);
        binding.backBtn.setOnClickListener(v -> finish());

        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm1 = priceAreaFooter.findViewById( R.id.bt_confirm);

        //点击重置
        cancel.setOnClickListener(v -> {
            timeAdapter.startTime = "";
            timeAdapter.endTime = "";
            startTime = "";
            endTime = "";
            binding.include.dropDownMenu.setTabText("约看日期");
            timeAdapter.notifyDataSetChanged();
        });

        //确定按钮
        confirm1.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
                jsonObject.put("appointmentStartTime", startTime);
                jsonObject.put("appointmentEndTime", endTime);
            } else {
                jsonObject.remove("appointmentStartTime");
                jsonObject.remove("appointmentEndTime");
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });

        //init customer menu
        final View customerFooter = this.getLayoutInflater().inflate(R.layout.item_search_footer, null);
        binding.include.dropDownMenu.setTabText(headers[2]);
        //约看人员输入框
        causeNumber = customerFooter.findViewById(R.id.search_edit);
        causeNumber.setHint("请输入客户姓名");
        //搜索按钮
        confirm = customerFooter.findViewById(R.id.search_text);

        //init popupViews
        popupViews.add(stateView);
        popupViews.add(timeView);
        popupViews.add(customerFooter);


        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.include.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.include.contractRecyclerView.setHasFixedSize(true);
        binding.include.contractRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.include.contractRecyclerView.enableAutoLoadMore(this);


        adapter = new AppointmentVisitAdapter(dataList);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.include.contractRecyclerView.setAdapter(adapter);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        stateView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                stateAdapter.setCheckItem(i);
                binding.include.dropDownMenu.setTabText(i == 0 ? headers[0] : state[i]);
                switch (i) {
                    case 0:
                        jsonObject.remove("state");
                        break;
                    case 1:
                        jsonObject.put("state", 0);
                        break;
                    case 2:
                        jsonObject.put("state", 1);
                        break;
                    case 3:
                        jsonObject.put("state", 3);
                        break;
                    case 4:
                        jsonObject.put("state", 2);
                        break;
                }
                getData();
                binding.include.dropDownMenu.closeMenu();
            }
        });
        timeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                show(time[i]);
                timeAdapter.setCheckItem(i);
                binding.include.dropDownMenu.setTabText(startTime + "—" + endTime);
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(causeNumber.getText().toString())) {
                    binding.include.dropDownMenu.setTabText("约看人员");
                    jsonObject.remove("customerName");
                    binding.include.dropDownMenu.closeMenu();
                } else {
                    binding.include.dropDownMenu.setTabText(causeNumber.getText().toString());
                    jsonObject.put("customerName", causeNumber.getText().toString());
                    binding.include.dropDownMenu.closeMenu();
                }
                getData();
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }
        });

        adapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object o) {
                Map<String, Object> map = (Map<String, Object>) o;
                Intent intent = new Intent(AppointmentVisitActivity.this, AppVisitDetailsActivity.class);
                intent.putExtra("appointmentCode", StringUtil.valueOf(map.get("appointmentCode")));
                intent.putExtra("sex", StringUtil.valueOf(map.get("sex")));
                startActivityForResult(intent,100);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( requestCode == 100 && resultCode == RESULT_OK ){
            page = 1;
            getData();
        }
    }

    public void onClick() {
        finish();
    }


    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = DateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = DateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.include.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.include.dropDownMenu.setTabText(startTime + endTime);
        }
    }

    public void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getSupportFragmentManager(), "year_month_day");
    }

    /**
     * 获取数据
     */
    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        OkHttpUtils
                .postString()
                .url(ApiConfig.APPOINTMENT_VISIT_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AppointmentVisitActivity.this, response, adapter)) {
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(response.get("data").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        } else if (response.get("code").toString().equals("501")) {
                            adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                        if (binding.include.refreshLayout.isRefreshing()) {
                            binding.include.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        }else{
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }
}
